<template>
    <u-popup ref="screenFang" v-model="localShow" mode="bottom" border-radius="32" height="85%" @close="closeDom">
        <view class="bodyDom" ref="screenFang">
            <view class="header flex_hc">
                <!-- <text class="shaixuan">筛选结果：<text style="font-size: 42rpx;
    color: red;">{{ total }}</text>套房源</text> -->
                <text>筛选</text>
                <u-icon class="closeDom" name="close" color="#020202" size="28" @click="closeDom"></u-icon>
            </view>
            <view class="body flex_row">
                <view class="leftTips">
                    <view v-for="(tips, index) in tipsList" :key="tips.id" v-show="tips.showType"
                        :class="['tipsItem', tipsIndex == index ? 'nowTips' : '']" @click="tipsClick(index)">{{
                            tips.name }}
                    </view>
                </view>
                <view class="rightBox" ref="rightBox">
                    <scroll-view scroll-y="true" style="height:100%" @scroll="onScroll">
                        <view :ref="'tips_' + index" v-for="(tips, index) in tipsList" :key="tips.id"
                            v-show="tips.showType" :class="tips.id">
                            <view class="TipsTitle">{{ tips.name }}</view>
                            <view class="flex_row itemDom">
                                <view v-for="(item, index) in tips.itemList" :key="index"
                                    :class="['tipsitem', item.isSelect ? 'nowtipsitem' : '']"
                                    @click="tipsItems(tips, item)">
                                    {{ item.name }}
                                </view>
                            </view>
                        </view>
                    </scroll-view>
                </view>
            </view>
            <!-- 底部按钮 -->
            <view class="BingoBut flex_row flex_vc">
                <view class="reset" @click="reset">重置</view>
                <view class="determine" @click="close(true)">确定({{ total }})</view>
            </view>
            <!-- 价格自定义弹窗 -->
            <u-popup v-model="priceShow" mode="bottom" border-radius="32" height="35%" @click.stop="closePrice">
                <view style="height: 100%;position: relative;">
                    <view class="header flex_hc">
                        <text>请输入价格区间</text>
                        <u-icon class="closeDom" name="close" color="#020202" size="28"
                            @click.stop="closePrice"></u-icon>
                    </view>
                    <view class="priceBody flex_row flex_vc" style="padding: 30rpx;">
                        <u-input v-model="priceStart" :type="number" placeholder="最低价" height="100" :border="true"
                            input-align="center" border-color="#10C595" style="width: 90%;" :clearable="false" />
                        <text style="width: 120rpx;text-align: center;font-size: 50rpx;">-</text>
                        <u-input v-model="priceEnd" :type="number" placeholder="最高价" height="100" :border="true"
                            input-align="center" border-color="#10C595" style="width: 90%;" :clearable="false" />
                    </view>
                    <view class="priceBut" @click="priceDetermine">确定</view>
                </view>
            </u-popup>
        </view>
    </u-popup>
</template>
<script>
import { mapActions } from 'vuex';
import { recommendList } from "@/api/home/home.js";
export default {
    name: 'screenFang',
    data() {
        return {
            locationData: uni.getStorageSync("locationData"),
            tipsIndex: 0,
            localShow: false, // 本地数据代替props的show
            tipsList: [],
            priceShow: false,//展示价格弹窗
            priceStart: null,//自定义价格开始
            priceEnd: null,//自定义价格结束
            queryParams: {},
            type: false,//自定义状态，判断是否要重新获取接口数据和点击确定按钮是否要跳转页面
            total: null,//筛选的结果数量
        }
    },
    methods: {
        ...mapActions(['updateTipsList']),//引入更新筛选条件方法
        async Ishow(type, noShowList) {
            // 将本地的 tipsList 设置为 Vuex 中的 tipsList
            let tipsList = this.$u.deepClone(this.$store.state.tipsList);
            console.log('拿到最新的筛选数组', this.tipsList);
            //判断是否需要调用接口获取最新数据
            this.type = type;//储存状态
            console.log('不要展示出来的数组', noShowList);
            // 过滤掉 noShowList 中的项
            if (noShowList && Array.isArray(noShowList)) {
                // tipsList = tipsList.filter(item => !noShowList.includes(item.name));
                tipsList.forEach(ips => {
                    noShowList.forEach(idd => {
                        if (ips.name == idd) {
                            ips.showType = false
                        } else {
                            ips.showType = true
                        }
                    })
                })
            }
            this.tipsList = tipsList
            setTimeout(() => {
                this.getrecommendList({})
            }, 40)
            this.localShow = true
        },
        //获取房源列表
        getrecommendList(item) {
            console.log('房源信息参数', item);
						const locationData = uni.getStorageSync('locationData')
						if (locationData) {
							item.lat = locationData.lat
							item.lng = locationData.lng
						}
            recommendList(item).then(res => {
                if (res.data.code === 200) {
                    console.log('获取到的房源数量', res.data);
                    this.total = res.data.total
                }
            })
        },
        //重置
        reset() {
            this.tipsList.forEach(tips => {
                tips.itemList.forEach(item => {
                    item.isSelect = false;
                });
            });
            // 更新 Vuex 中的 tipsList
            this.updateTipsList(this.tipsList);
        },
        closeDom() {
            this.localShow = false
        },
        //点击条件请求接口获取结果数量展示
        getNumbyData() {
            console.log('要处理的数组', this.tipsList);
            // 更新 Vuex 中的 tipsList
            this.updateTipsList(this.tipsList);
            let item = {
							 distance: '',      // 距离
							 rentStartPrice: '',// 最小金额
							 rentEndPrice: '',  // 最大金额
							 typeIds: '',       // 房屋类型
							 rentStatuses: '',    // 0空闲1可预定2已预定
                sourceIds: '',     // 来源
                landmarkIds: '',   // 地标
            };
            // 映射索引到字段名称
            const fieldMap = {
                0: 'distance',
                1: 'price',        // 特殊处理价格
                2: 'typeIds',
                3: 'rentStatuses',    // 特殊处理状态
								4: 'sourceIds',
								5: 'landmarkIds',
            };
            // 处理选项的通用逻辑
            const processSelection = (itemList) => {
                return itemList
                    .filter(itt => itt.isSelect)
                    .map(itt => itt.id)
                    .toString();
            };
            setTimeout(() => {
                // 遍历处理每个选项
                this.tipsList.forEach((ite, index) => {
                    const field = fieldMap[index];
                    if (field === 'price') {
                        // 处理价格区间
                        const priceItem = ite.itemList.find(itt => itt.isSelect);
                        if (priceItem) {
                            item.rentStartPrice = priceItem.rentStartPrice || 0;
                            item.rentEndPrice = priceItem.rentEndPrice || 0;
                        }
                    } else if (field === 'rentStatuses') {
                        // 处理状态选项
                        let ids = processSelection(ite.itemList);
                        item.rentStatuses = ids.length === 2 ? '' : ids;
                    } else {
                        // 处理其他选项
                        item[field] = processSelection(ite.itemList);
                    }
                });
                console.log('当前选择的全部参数', item);
                //获取房源数据
                this.getrecommendList(item)
            }, 20);

        },
        close(type) {
            if (type) {
                console.log('要处理的数组', this.tipsList);
                // 更新 Vuex 中的 tipsList
                this.updateTipsList(this.tipsList);
                let item = {
                	 distance: '',      // 距离
                	 rentStartPrice: '',// 最小金额
                	 rentEndPrice: '',  // 最大金额
                	 typeIds: '',       // 房屋类型
                	 rentStatuses: '',    // 0空闲1可预定2已预定
                    sourceIds: '',     // 来源
                    landmarkIds: '',   // 地标
                };
                // 映射索引到字段名称
                const fieldMap = {
                    0: 'distance',
                    1: 'price',        // 特殊处理价格
                    2: 'typeIds',
                    3: 'rentStatuses',    // 特殊处理状态
                		4: 'sourceIds',
                		5: 'landmarkIds',
                };
                // 处理选项的通用逻辑
                const processSelection = (itemList) => {
                    return itemList
                        .filter(itt => itt.isSelect)
                        .map(itt => itt.id)
                        .toString();
                };
                // 遍历处理每个选项
                this.tipsList.forEach((ite, index) => {
                    const field = fieldMap[index];
                    if (field === 'price') {
                        // 处理价格区间
                        const priceItem = ite.itemList.find(itt => itt.isSelect);
                        if (priceItem) {
                            item.rentStartPrice = priceItem.rentStartPrice || 0;
                            item.rentEndPrice = priceItem.rentEndPrice || 0;
                        }
                    } else if (field === 'rentStatuses') {
                        // 处理状态选项
                        let ids = processSelection(ite.itemList);
                        item.rentStatuses = ids.length === 2 ? '' : ids;
                    } else {
                        // 处理其他选项
                        item[field] = processSelection(ite.itemList);
                    }
                });
                console.log('当前选择的全部参数', item);
                //去到房屋列表页面
                if (this.type) { //首页点击组件的确定要跳转到房屋列表页面
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages/mall/house/house' + this.$u.queryParams(item)
                        })
                    }, 200);
                }
                this.$emit('Close', item);
                this.localShow = false
            } else {
                this.$emit('Close', false);
                this.localShow = false

            }
        },
        //左边类型切换
        tipsClick(index) {
            this.tipsIndex = index;
            const targetRef = `tips_${index}`;
            this.$nextTick(() => {
                // 获取右侧对应的模块
                const targetElement = this.$refs[targetRef]?.[0]; // 如果是数组，需要取第一个元素
                console.log('要展示出来的dom', targetRef, this.$refs['tips_1']);
                if (targetElement) {
                    targetElement.scrollIntoView({ behavior: 'smooth' });
                }
            });
        },
        //类型选中
        tipsItems(tips, item) {
            //判断点击的是不是自定义
            if (item.name == '自定义') {
                // 判断类型
                switch (item.type) {
                    case '价格':  //价格的自定义功能
                        console.log('当前要走的是价格的自定义模块');
                        this.priceShow = true
                        break;
                    default:
                        break;
                }
            } else {
                //要判断当前模块的类型来确定是单选还是多选  默认就是多选，ClickType true单选
                if (tips.ClickType) {  //是单选，要重置当前其他模块的选中效果
                    tips.itemList.forEach(element => {
                        // this.$set(element, 'isSelect', false)
                        element.isSelect = false
                    });
                    //当前点击的那项变成true
                    // this.$nextTick(() => {
                    item.isSelect = true
                    // this.$set(item, 'isSelect', true)
                    // })
                } else { //多选
                    if (item.isSelect) {
                        item.isSelect = false
                    } else {
                        // this.$set(item, 'isSelect', true)
                        item.isSelect = true
                    }
                }
            }
            this.getNumbyData()
        },
        // 右侧滚动事件
        onScroll(event) {
            const scrollTop = event.detail.scrollTop;
            let index = 0;
            // 遍历右侧内容，根据滚动位置设置左侧选中状态
            for (let i = 0; i < this.tipsList.length; i++) {
                const targetRef = `tips_${i}`;
                const targetElement = this.$refs[targetRef]?.[0]; // 获取每个目标元素
                if (targetElement) {
                    const elementTop = targetElement.getBoundingClientRect().top;
                    if (elementTop <= scrollTop) {
                        index = i;
                    }
                }
            }
            this.tipsIndex = index;
        },
        //关闭自定义价格区间弹窗
        closePrice() {
            this.priceShow = false
        },
        //自定义价格确定
        priceDetermine() {
            // 如果开始价格大于结束价格，交换两者
            // 将输入的字符串类型价格转换为数字类型
            let startPrice = parseFloat(this.priceStart);
            let endPrice = parseFloat(this.priceEnd);
            if (startPrice > endPrice) {
                // 交换 startPrice 和 endPrice
                let temp = startPrice;
                startPrice = endPrice;
                endPrice = temp;
            }
            // 将转换后的价格重新赋值给对应的变量
            this.priceStart = startPrice;
            this.priceEnd = endPrice;
            // 生成新的自定义价格项
            const customPriceItem = {
                name: `${this.priceStart}元-${this.priceEnd}元`,
                id: new Date().getTime().toString(), // 使用时间戳作为唯一ID
                rentStartPrice: this.priceStart,
                rentEndPrice: this.priceEnd,
                isSelect: true // 设置为选中状态
            };
            // 价格是单选,将所有其他项的 isSelect 设为 false
            this.tipsList[1].itemList.forEach(item => {
                item.isSelect = false;
            });
            // 在自定义按钮前面插入新的自定义价格项
            this.tipsList[1].itemList.splice(this.tipsList[1].itemList.length - 1, 0, customPriceItem);
            this.priceShow = false
            //关闭自定义价格窗口后，清除上次输入的自定义价格
            this.priceStart = ''
            this.priceEnd = ''
        }
    }
}
</script>
<style scoped lang="scss">
@import "@/static/scss/flex.scss";

.bodyDom {
    height: 100%;
    position: relative;

    .header {
        position: relative;
        padding: 40rpx;

        text {
            font-weight: bold;
            font-size: 32rpx;
            color: #333333;
        }

        .closeDom {
            position: absolute;
            right: 30rpx;
        }

        .shaixuan {
            position: absolute;
            left: 30rpx;
        }
    }

    .body {
        height: calc(100% - 320rpx);

        .leftTips {
            width: 154rpx;
            background: #F6F6F6;
            height: 100%;

            .tipsItem {
                font-size: 28rpx;
                color: #666666;
                width: 100%;
                line-height: 80rpx;
                text-align: center;
            }

            .nowTips {
                background-color: #FFFFFF;
            }
        }

        .rightBox {
            flex: 1;
            height: 100%;
            padding: 24rpx;

            .TipsTitle {
                font-weight: bold;
                font-size: 28rpx;
                color: #333333;
            }

            .itemDom {
                gap: 20rpx;
                flex-wrap: wrap;
                margin-top: 30rpx;
                margin-bottom: 50rpx;

            }

            .tipsitem {
                background: #F6F6F6;
                border-radius: 4rpx;
                // max-width: 330rpx;
                min-height: 68rpx;
                // line-height: 68rpx;
                // text-align: center;
                font-size: 28rpx;
                color: #333333;
                padding: 0 18rpx;
                border: 2rpx solid #F6F6F6;
                box-sizing: border-box; // 确保边框不会增加尺寸
                display: flex;
                align-items: center;
            }

            .nowtipsitem {
                color: #10C595;
                border: 2rpx solid #10C595;
                box-sizing: border-box; // 确保边框不会增加尺寸
            }
        }
    }

    .priceBut {
        height: 80rpx;
        width: 90%;
        background: #10C595;
        border-radius: 16rpx;
        line-height: 80rpx;
        text-align: center;
        font-size: 28rpx;
        color: #FFFFFF;
        position: absolute;
        bottom: 80rpx;
        left: 5%;
    }

    .BingoBut {
        width: 100%;
        font-size: 28rpx;
        color: #FFFFFF;
        position: absolute;
        bottom: 70rpx;
        gap: 30rpx;
        background: #ffffff;
        padding: 20rpx;

        .reset {
            width: 247rpx;
            background: #EFF5F9;
            border-radius: 16rpx;
            color: #333333;
            line-height: 80rpx;
            text-align: center;
        }

        .determine {
            background: #10C595;
            border-radius: 16rpx;
            line-height: 80rpx;
            flex: 1;
            text-align: center;
        }
    }
}
</style>
